package com.agileboot.api.customize.service;

import com.agileboot.common.exception.ApiException;
import com.agileboot.common.exception.error.ErrorCode;
import com.agileboot.common.utils.http.HttpTemplate;
import com.agileboot.domain.system.user.UserApplicationService;
import com.agileboot.domain.system.user.db.SysUserEntity;
import com.agileboot.domain.system.user.dto.WxSeeionDTO;
import com.agileboot.domain.system.user.dto.WxUserInfoDTO;
import com.agileboot.infrastructure.user.app.AppLoginUser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class AppLoginService {

    @Value("${wxInfo.APP_ID}")
    private String appid;

    @Value("${wxInfo.SECRET_KEY}")
    private String secret;
    private final UserApplicationService userApplicationService;

    private final JwtTokenService jwtTokenService;

    public SysUserEntity loginAppUser(String code) throws JsonProcessingException {
        String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appid, secret, code
        );
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = HttpTemplate.httpGet(url);
//        System.out.println(jsonString);
        WxSeeionDTO wxSeeionDTO = objectMapper.readValue(jsonString, WxSeeionDTO.class);
//        System.out.println(wxSeeionDTO.getErrcode());
        if(wxSeeionDTO.getErrcode()!=null) retLoginErrmsg(wxSeeionDTO.getErrcode());
        if(wxSeeionDTO.getOpenid()!=null){
            userApplicationService.loadByOpenId(wxSeeionDTO.getOpenid());
        }else{
            throw new ApiException(ErrorCode.Business.USER_WX_CODE_NULL);
        }
        SysUserEntity userEntity = userApplicationService.getWxUserInfo(wxSeeionDTO.getOpenid());
        if(userEntity==null){
            throw new ApiException(ErrorCode.Business.USER_WX_CODE_NULL_OPENID);
        }
        return userEntity;
    }

    /**
     * 根据token获取小程序用户信息
     * @return
     */
    public WxUserInfoDTO getWxUserInfo(){
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        AppLoginUser appLoginUser = jwtTokenService.getLoginAppUser(request);
        return userApplicationService.getWxUserInfoDTO(appLoginUser.getUserId());
    }

    /**
     * 小程序登录错误码
     * @param errcode
     */
    private void retLoginErrmsg(Integer errcode){
        if(errcode==40029) throw new ApiException(ErrorCode.Business.USER_WX_CODE_NULL);
        if(errcode==45011) throw new ApiException(ErrorCode.Business.USER_WX_CODE_NULL_API);
        if(errcode==40226) throw new ApiException(ErrorCode.Business.USER_WX_CODE_NULL_BLOCKED);
        if(errcode==-1) throw new ApiException(ErrorCode.Business.USER_WX_CODE_NULL_SYSTEM);
        if(errcode==40163) throw new ApiException(ErrorCode.Business.USER_WX_CODE_NULL_USED);
    }




}
